// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const orders = db.collection('orders')
  const openid = wxContext.OPENID

  try {
    // 生成订单号
    const orderNo = generateOrderNo()
    
    // 组装订单数据
    const orderData = {
      _openid: openid,
      order_no: orderNo,
      address: event.address,
      items: event.goods,
      amount: event.totalAmount,
      shipping_fee: event.shippingFee || 0,
      remark: event.remark || '',
      status: 'pending',
      payment_status: 'unpaid',
      created_at: new Date(),
      updated_at: new Date()
    }

    // 写入订单
    const res = await orders.add({ data: orderData })
    
    return {
      success: true,
      orderId: res._id,
      orderNo: orderNo,
      message: '订单创建成功'
    }
  } catch (error) {
    console.error('创建订单失败：', error)
    return {
      success: false,
      message: '订单创建失败'
    }
  }
}

// 生成订单号
function generateOrderNo() {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hour = String(now.getHours()).padStart(2, '0')
  const minute = String(now.getMinutes()).padStart(2, '0')
  const second = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `${year}${month}${day}${hour}${minute}${second}${random}`
} 